import { ref } from "vue";
import api from "@/utils";
import { AxiosResponse } from "axios";
import { ElMessage } from "element-plus";

// 表单数据的操作.
export default function DataOption() {
  // 获取的数据
  const data = ref([]);

  // 上次查询的url, 刷新时将生效.
  const lastUrl = ref("");

  // 上次搜索筛选内容, 刷新时起作用.
  const lastSearchData = ref({});

  // 获取表单数据.
  const getRecord = async (
    url?: string,
    searchData?: Record<string, unknown>
  ) => {
    if (url === null || url === undefined) {
      url = lastUrl.value;
    }
    if (searchData === null || searchData === undefined) {
      searchData = lastSearchData.value;
    }

    // const websocket = Websocket();
    // websocket.connect(url);

    await api.http
      .postJson(url, searchData)
      .then((res: AxiosResponse) => {
        console.log(res);
        data.value = res.data.data;
        lastUrl.value = url as string;
        lastSearchData.value = searchData as Record<string, unknown>;
      })
      .catch((err) => {
        console.log(err);
        ElMessage.error("系统错误,请联系管理员!");
      });
  };

  return { data, getRecord };
}
